<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->

      <el-row>
        <el-col :span="7">
          <!-- 输入框和搜索 -->
          <el-input
            placeholder="请输入内容"
            v-model="userinfo.query"
            clearable
            @clear="getuserinfo"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getuserinfo"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="4">
          <el-button type="primary" class="yidong" @click="addDialog = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" class="tables" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- 重点   作用域 插槽 -->
          <template v-slot="scope">
            <!-- {{ scope.row }} -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template v-slot="scope">
            <!-- {{ scope.row }} -->
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="xiugaianniu(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="remove(scope.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="getfenPei(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userinfo.pagenum"
        :page-sizes="[1, 2, 5, 12]"
        :page-size="userinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialog"
      width="30%"
      @close="addclosedialog"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addFrom"
        :rules="addFromRules"
        ref="addFromRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addFrom.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addFrom.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <!-- 添加用户 设置 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="querenadd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色  对话框 -->
    <el-dialog title="分配角色" :visible.sync="fenPusers" width="50%" @close="setdiglogclose">
      <div>
        <p>当前的用户:{{ userInfo.username }}</p>
        <p>当前的角色:{{ userInfo.role_name }}</p>
        <p>
          分配新角色:
          <el-select v-model="newRoles" placeholder="请选择">
            <el-option
              v-for="item in userslist"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="fenPusers = false">取 消</el-button>
        <el-button type="primary" @click="saveRolesinfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editdialog"
      width="50%"
      @close="editdialogclose"
    >
      <el-form
        :model="editFrom"
        :rules="editFromrules"
        ref="editFromref"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editFrom.username" disabled></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editFrom.email"></el-input>
        </el-form-item>
        <!-- 电话 -->
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editdialog = false">取 消</el-button>
        <el-button type="primary" @click="edituserinfo()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 邮箱的验证规则
    var checkEmail = (rule, value, cb) => {
      const regEmail =
        /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };

    //  手机号的验证规则
    var checkPhone = (rule, value, cb) => {
      const regPhone = /^(?:(?:\+|00)86)?1\d{10}$/;
      if (regPhone.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };

    return {
      // 已选中的角色的id
      newRoles: "",
      // 所有角色的数据列表
      userslist: [],
      // 需要被分配权限的用户的信息
      userInfo: {},
      // 分配角色的显示与隐藏
      fenPusers: false,
      // 获取用户列表的参数对象
      userinfo: {
        // 搜索关键词
        query: "",
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少数据
        pagesize: 2,
      },
      editdialog: false,
      //   获取用户的信息
      userlist: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialog: false,
      // 添加用户的表单数据
      addFrom: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 修改用户
      userId: "",
      editFrom: {},
      // 添加表单的验证规则对象
      addFromRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名的长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "密码的长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          // 验证邮箱
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          // 验证手机号
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" },
        ],
      },
      // 修改表单的验证规则
      editFromrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名的长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          // 验证邮箱
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          // 验证手机号
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" },
        ],
      },
      // 根据id请求数据
      // idadd: {},
    };
  },
  created() {
    this.getuserinfo();
  },
  methods: {
    async getuserinfo() {
      // params  get 请求
      const { data: res } = await this.$http.get("users", {
        params: this.userinfo,
      });
      // console.log("-=-", res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败");
      } else {
        this.userlist = res.data.users;
        this.total = res.data.total;
      }
    },
    // 监听  pagesize 的改变
    handleSizeChange(newSize) {
      // console.log("123==", newSize);
      this.userinfo.pagesize = newSize;
      this.getuserinfo();
    },
    // 监听  页码值改变的事件
    handleCurrentChange(newPage) {
      // console.log("456==", newPage);
      this.userinfo.pagenum = newPage;
      this.getuserinfo();
    },
    // 监听  switch 开关状态的改变
    async userChange(usexinxi) {
      // console.log("-=-=-=-=-", usexinxi);
      // 模板字符串
      const { data: res } = await this.$http.put(
        `users/${usexinxi.id}/state/${usexinxi.mg_state}`
      );
      if (res.meta.status !== 200) {
        // 重点
        usexinxi.mg_state = !usexinxi.mg_state;
        this.$message.error("更新用户状态失败");
      } else {
        this.$message.success("更新用户状态成功");
      }
    },
    // 监听     refs   添加用户对话框的关闭事件
    addclosedialog() {
      this.$refs.addFromRef.resetFields();
    },
    // 点击按钮,添加新用户
    querenadd() {
      this.$refs.addFromRef.validate(async (valid) => {
        // console.log('88888',valid)
        if (!valid) return;
        // 发起添加用户的网络请求
        const { data: res } = await this.$http.post("users", this.addFrom);
        // console.log("123", res);
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败");
        } else {
          this.$message.success("添加用户成功");
          //  隐藏添加用户的对话框
          this.addDialog = false;
          // 渲染界面
          this.getuserinfo();
        }
      });
    },
    // 展示编辑用户的对话框
    async xiugaianniu(id) {
      //  console.log('989898',id)
      this.editdialog = true;
      this.userId = id;
      const { data: res } = await this.$http.get(`users/${id}`);
      // console.log("123456", res);
      if (res.meta.status !== 200) {
        return this.$message.error("请求数据失败");
      } else {
        this.editFrom = res.data;
      }
    },
    // 监听修改用户对话框的关闭事件
    editdialogclose() {
      this.$refs.editFromref.resetFields();
    },
    // 修改用户信息并        提交      必须要预验证
    edituserinfo() {
      this.$refs.editFromref.validate(async (valid) => {
        // console.log('1234568',valid)
        if (!valid) return;
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$http.put("users/" + this.userId, {
          id: this.userId,
          email: this.editFrom.email,
          mobile: this.editFrom.mobile,
        });
        console.log("888888", res);
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);

        // if(res.meta.status !==200){
        //   return this.$message.error(res.meta.msg)
        // }else{
        //   this.$message.success(res.meta.msg)
        // }
        // 关闭对话框
        this.editdialog = false;
        // 刷新数据列表   上传
        this.getuserinfo();
      });
      // 修改 提交
      // if(res.meta.status !== 200){
      //   return this.$message.error('更新用户信息失败')
      // }
      // 关闭对话框
      // this.editdialog = false;
      // 刷新数据列表
      //  this.getuserinfo()
      //  提示修改成功
      // this.$message.success('更新用户信息成功')
    },
    // 删除操作
    async remove(id) {
      const resremove = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);
      // console.log("0000", resremove);
      // 确定是confirm  取消是cancel
      if (resremove !== "confirm") {
        return this.$message.info("已取消删除");
      } else {
        // console.log('已确认删除')
        const { data: res } = await this.$http.delete(`users/${id}`);
        console.log("00000", res);
        if (res.meta.status !== 200) {
          return this.$message.error("删除用户失败");
        } else {
          // 刷新数据
          this.getuserinfo();
          this.$message.success("删除用户成功");
        }
      }
    },
    // 展示分配角色的对话框
    async getfenPei(userInfo) {
      this.userInfo = userInfo;
      this.fenPusers = true;
      const { data: res } = await this.$http.get("roles");
      console.log("展示分配角色的对话框", res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      } else {
        this.userslist = res.data;
      }
    },
    // 点击按钮分配角色
    async saveRolesinfo() {
      if (!this.newRoles) {
        return this.$message.error("请选择要分配的角色");
      }
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        { rid: this.newRoles,}
      );
      console.log('999',res)
      if(res.meta.status!==200){
        return this.$message.error('更新角色失败')
      }else{
        this.$message.success('更新用户成功')
        this.getuserinfo();
        this.fenPusers = false
      }
    },
    // 监听分配角色对话框的关闭事件
    setdiglogclose(){
      this.newRoles = '',
      this.userInfo = {}
    }
  },
};
</script>

<style lang="less" scoped>
.box-card {
  margin-top: 15px;
}
.yidong {
  margin-left: 20px;
}
.tables {
  margin-top: 10px;
  font-size: 13px;
}
.el-pagination {
  margin-top: 15px;
  text-align: center;
}
</style>